package com.wmx.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * http请求工具类
 */
@Slf4j
public class HttpClientTools {
    public static final CloseableHttpClient httpClient;
    private static final String CHARSET_UTF8 = "UTF-8";
    private static final String APPLICATION_JSON = "application/json";
    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
    private static final int CONNECT_TIME_OUT = 5000 * 2;
    private static final int SOCKET_TIME_OUT = 2 * 60 *1000;//会话时间1分钟

    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECT_TIME_OUT).setSocketTimeout(SOCKET_TIME_OUT).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }


    public static String doGet(String url) {
        System.out.println("=========请求地址======="+url);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = "";
        try {
            HttpGet httpget = new HttpGet(url);
            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
                public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        return entity != null ? EntityUtils.toString(entity) : null;
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };
            result = httpclient.execute(httpget, responseHandler);
        } catch (Exception e) {
            return "ERROR";
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                return "ERROR";
            }
        }
        return result;
    }







}
